package com.phrp.service.impl;

import com.phrp.common.ConstantNumber;
import com.phrp.entity.dto.InspectionDataDTO;
import com.phrp.entity.vo.InspectionSearchDataVO;
import com.phrp.exception.CustomizationException;
import com.phrp.util.returnResult.ReturnInfoEnum;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.phrp.common.ConstantEnum;
import com.phrp.dao.ManagerUserDao;
import com.phrp.entity.InspectionRecord;
import com.phrp.dao.InspectionRecordDao;
import com.phrp.entity.vo.PageData;
import com.phrp.service.InspectionRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.phrp.util.returnResult.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ssc
 * @since 2024-05-03
 */
@Service
public class InspectionRecordServiceImpl extends ServiceImpl<InspectionRecordDao, InspectionRecord> implements InspectionRecordService {

    @Autowired
    private InspectionRecordDao inspectionRecordDao;

    @Autowired
    private ManagerUserDao managerUserDao;

    /**
     * 根据条件搜索数据
     *
     * @param searchData
     * @return
     */
    @Override
    public ResponseResult getSearchData(InspectionSearchDataVO searchData) {
        searchData.setStartPage((searchData.getCurrentPage() - 1) * searchData.getPageSize());
        LinkedList<InspectionDataDTO> datas = inspectionRecordDao.selectBySearchData(searchData);
        Integer totalNum = inspectionRecordDao.getTotalNum(searchData);

        PageData<LinkedList<InspectionDataDTO>> pageData = new PageData<>();
        pageData.setData(datas);
        pageData.setTotalNumber(totalNum);

        return new ResponseResult(ReturnInfoEnum.SUCCESS, pageData);
    }

    /**
     * 新增巡查数据
     *
     * @param mUuid
     * @param hUuid
     * @param inspectionTime
     * @return
     */
    @Transactional(rollbackFor = CustomizationException.class)
    @Override
    public ResponseResult insertInspection(String mUuid, String hUuid, String inspectionTime) {
        InspectionRecord inspectionRecord = new InspectionRecord();
        // 解析字符串为 ZonedDateTime 对象
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(inspectionTime, DateTimeFormatter.ISO_DATE_TIME);
        // 将 ZonedDateTime 转换为 LocalDateTime
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
        inspectionRecord.setInspectionTime(localDateTime);

        inspectionRecord.setHUuid(hUuid);
        inspectionRecord.setMUuid(mUuid);
        inspectionRecord.setIUuid(UUID.randomUUID().toString().replace("-", ""));

        int insert = inspectionRecordDao.insert(inspectionRecord);

        if (insert != 1) {
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        // 当新增成功后需要修改巡查员的次数
        int update = managerUserDao.updateInspectionNumberById(mUuid, ConstantNumber.inspectionAdd);

        if (update != 1) {
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 修改巡查信息
     * @param inspection
     * @return
     */
    @Override
    public ResponseResult editInspection(InspectionRecord inspection) {
        if (ConstantEnum.PUBLISH_INSPECTION.getCode().equals(inspection.getStatus())) {
            // 已经完成任务，需要修改巡查员的巡查数量
            int i = managerUserDao.updateInspectionNumberById(inspection.getMUuid(),ConstantNumber.inspectionMinus);
            if(i != 1){
                throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
            }
        }

        UpdateWrapper<InspectionRecord> update = new UpdateWrapper<>();
        update.eq("i_uuid",inspection.getIUuid())
                .set("h_uuid",inspection.getHUuid())
                .set("m_uuid",inspection.getMUuid())
                .set("inspection_time",inspection.getInspectionTime())
                .set("status",inspection.getStatus());

        if (inspection.getInspectionResult() != null && inspection.getInspectionResult() != "") {
            update.set("inspection_result",inspection.getInspectionResult());
        }

        int i = inspectionRecordDao.update(null, update);
        if(i != 1){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 删除巡查数据
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = CustomizationException.class)
    @Override
    public ResponseResult deleteInspection(List<String> ids,List<String> mUuids) {
        int i = inspectionRecordDao.deleteBatchIds(ids);

        if(i != ids.size()){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        int update = 0;
        for (String id : mUuids) {
            int i1 = managerUserDao.updateInspectionNumberById(id, ConstantNumber.inspectionMinus);
            update += i1;
        }
        if(update != ids.size()){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }
}
